import 'package:dio/dio.dart';
import 'package:gbk_codec/gbk_codec.dart';

import '../../logger.dart';

///
/// 使用网易服务
const String NS_TOOLS_URI = 'https://only-928106-111-197-63-16.nstool.netease.com/';

class Overt {
  ///
  /// 出站IP
  final String ip;
  ///
  /// local dns地址
  final String localDns;
  Overt(this.ip, this.localDns);
}

///
/// gbk decoder（网易的nstools使用gbk编码）
String _gbkDecoder(List<int> responseBytes, RequestOptions options,
    ResponseBody responseBody) {
  return gbk_bytes.decode(responseBytes);
}

///
/// 获取出站信息，包括出站IP地址和Local DNS地址
Future<Overt> getOvert() async {
  try {
    BaseOptions options = new BaseOptions();
    options.connectTimeout = 10000;
    options.receiveTimeout = 10000;
    final dioInst = new Dio(options);
    final response = await dioInst.get(
        NS_TOOLS_URI,
        options: Options(responseDecoder: _gbkDecoder));
    final text = response.toString();
    final ip = _peekIp(text, '您的IP地址信息: ');
    final localDns = _peekIp(text, '您的DNS地址信息: ');
    return Overt(ip, localDns);
  } on Exception catch (err) {
    Logger.e(msg: err);
    return null;
  }
}

///
/// 从nstools的text中提取IP信息
String _peekIp(String text, String starter) {
  try {
    final start = text.indexOf(starter) + starter.length;
    final secondHalf = text.substring(start);
    final end = secondHalf.indexOf(' ');
    return secondHalf.substring(0, end);
  } on Exception catch(err) {
    Logger.e(msg: err);
    return null;
  }
}